//
//  KRConversationViewController.m
//  KingrayTone_ios
//
//  Created by XiongYingqi on 14-5-27.
//  Copyright (c) 2014年 XiongYingqi. All rights reserved.
//

#import <sys/ucred.h>
#import "KRConversationViewController.h"
#import "KRChatViewController.h"
#import "KRAppDelegate.h"
#import "DDLog.h"
#import "XYQDrawPersonImage.h"
#import "KRConversationTextLabel.h"


// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
  static const int ddLogLevel = LOG_LEVEL_INFO;
#endif

@interface KRConversationViewController ()

@end

@implementation KRConversationViewController

NSMutableArray *conversations;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization

    }
    return self;
}

/**
* xib初始化会调用该方法
*/
-(id)initWithCoder:(NSCoder *)aDecoder {
    conversations = [[NSMutableArray alloc] init];
    [KRChatViewController setDelegate:self];
    [self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];
    NSLog(@" ------------------ conversation init ------------------ ");
    return [super initWithCoder:aDecoder];
}

- (void)viewDidLoad
{
    self.title = @"会话列表";

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"conversations.count ======= %@", conversations);
    return conversations.count;
}

- (void)configurePhotoForCell:(UITableViewCell *)cell user:(XMPPUserCoreDataStorageObject *)user {
    // Our xmppRosterStorage will cache photos as they arrive from the xmppvCardAvatarModule.
    // We only need to ask the avatar module for a photo, if the roster doesn't have it.

    if (user.photo != nil) {
        cell.imageView.image = user.photo;
    } else {
        NSData *photoData = [[[KRAppDelegate appDelegate] xmppvCardAvatarModule] photoDataForJID:user.jid];

        if (photoData != nil) {

            cell.imageView.image = [UIImage imageWithData:photoData];
        }
        else {
//            cell.imageView.image = [UIImage imageNamed:@"defaultPerson"];
            cell.imageView.image = [[[XYQDrawPersonImage alloc] init] getPersonImage:user.displayName];
//            cell.imageView.image = [[[XYQDrawPersonImage alloc] init] getImage];

        }
    }
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"UITableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    KRChatViewController *chatViewController = [conversations objectAtIndex:indexPath.row];

    XMPPUserCoreDataStorageObject *user = chatViewController.withUser;
    XMPPRoomMessageCoreDataStorageObject *messageCoreDataStorageObject = [[[chatViewController fetchedResultsController] fetchedObjects] firstObject];


    NSString *userName = user.displayName;
    NSString *conversationMessage = nil;

    if(messageCoreDataStorageObject.body){
//        conversationMessage = [[[conversationMessage stringByAppendingString:@"（"] stringByAppendingString:messageCoreDataStorageObject.body] stringByAppendingString:@"）"];
        conversationMessage = messageCoreDataStorageObject.body;
    }

//    KRConversationTextLabel *textLabel = [KRConversationTextLabel init:user.displayName withConversation:conversationMessage];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",  userName];
    cell.detailTextLabel.textAlignment = NSTextAlignmentRight;
    cell.detailTextLabel.textColor = [UIColor grayColor];
    cell.detailTextLabel.text = conversationMessage;
//    cell.separatorInset = UIEdgeInsetsMake(20.0f, 0.0f, 20.0f, 0.0f);
//    cell.textLabel = textLabel;
//    UILabel *label = [[UILabel alloc] init];
//    label.text = conversationMessage;
//    [cell.textLabel addSubview:label];


    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [self configurePhotoForCell:cell user:user];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KRChatViewController *chatViewController = [conversations objectAtIndex:indexPath.row];
//    [chatViewController setHidesBottomBarWhenPushed:YES];
    [[self navigationController] pushViewController:chatViewController animated:true];
}


- (void)chatViewOpened:(KRChatViewController *)chatViewController {
    NSLog(@" -------------- chatViewOpened -------------- ");
//    [conversations addObject:chatViewController];
//    NSLog(@"conversations ========= %@", conversations);
//    if(conversations && conversations.count > 0){
//        KRChatViewController *firstViewController = [conversations objectAtIndex:0];
//        if(firstViewController){
////            [conversations insertObject:firstViewController atIndex:1];
//            [conversations setObject:firstViewController atIndexedSubscript:1];
//        }
//    }

//    [conversations setObject:viewController atIndexedSubscript:1];

    [conversations insertObject:chatViewController atIndex:0];
    [self.tableView reloadData];
}

- (void)chatViewClosed:(KRChatViewController *)chatViewController {
    NSLog(@" -------------- chatViewClosed -------------- ");
    NSInteger index = [conversations indexOfObject:chatViewController];
    if(index != 0){
        [conversations removeObject:chatViewController];
    }
    [self.tableView reloadData];
}

- (void)conversationUpdated:(KRChatViewController *)chatViewController {
    NSLog(@" -------------- conversationUpdated -------------- ");
//    if(conversations && conversations.count > 0){
//        KRChatViewController *firstViewController = [conversations objectAtIndex:0];
//        if(firstViewController){
////            [conversations insertObject:firstViewController atIndex:1];
//            [conversations setObject:firstViewController atIndexedSubscript:1];
//        }
//    }
    NSInteger index = [conversations indexOfObject:chatViewController];
    NSLog(@" index -------------- %d", index);
    NSLog(@" chatViewController -------------- %@", chatViewController);
    if(index != 0){
        [conversations removeObject:chatViewController];
        [conversations insertObject:chatViewController atIndex:0];
    }
    [self.tableView reloadData];

}


@end
